import router from '@/router'
import { useUserStore } from '@/stores/user'
import axios, { type Method } from 'axios'
import { ElMessage } from 'element-plus'



type ServiceResponse<T> = {
  data: T
  message: string
}

 export const service = axios.create({
  baseURL: 'https://geek.itheima.net',
  timeout: 5000,
})

service.interceptors.request.use(confirm=> {
    const {token} = useUserStore()
    if(token)confirm.headers.Authorization = `Bearer ${token}`

    return confirm
  },error => {
    return Promise.reject(error)
  })

service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    if (error.response.status === 401) {
      useUserStore().removeToken()
      ElMessage.error('登录过期，请重新登录')
      router.push('/login')
    }
    return Promise.reject(error)
  })

export const request = <T>(url: string, method: Method = 'GET', data?: object) => {
  return service.request<T, ServiceResponse<T>>({
    url,
    method,
    // 导出一个通用的请求工具函数
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: data,
  })
}


